package com.edu.cdp.service.impl;

import com.edu.cdp.DTO.PageDTO;
import com.edu.cdp.DTO.UpdateUserDTO;
import com.edu.cdp.DTO.UserDTO;
import com.edu.cdp.VO.BalanceVO;
import com.edu.cdp.common.PageResult;
import com.edu.cdp.service.CommonService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.cdp.domain.User;
import com.edu.cdp.service.UserService;
import com.edu.cdp.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Yang Can
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-05-31 11:27:57
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    UserMapper userMapper;
    @Autowired
    CommonService commonService;
    @Override
    public User login(String username, String password) {
        QueryWrapper<User> query = new QueryWrapper<User>();

        query.eq("name", username);
        query.eq("password", password);

        User user = userMapper.selectOne(query);

        if (user != null) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("email", userDTO.getEmail());

        List<User> users = userMapper.selectByMap(map);

        if (users.size() >= 2) {
            log.error("每个邮箱最多只能注册两个账户");

            return null;
        } else {
            User user = new User();
            //用户信息复制
            BeanUtils.copyProperties(userDTO, user);
            //设置用户默认信息
            user.setAvatar(null);
            user.setPhone("用户未设置");
            user.setSex("男");
            user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
             int result = userMapper.insert(user);
             if (result > 0) {
                 return user;
             } else {
                 log.error("注册失败");
                 return null;
             }
        }
    }

    @Override
    public List<User> getUserByName(String userName) {
      QueryWrapper<User> query = new QueryWrapper<User>();

      query.like("name", userName);

        return userMapper.selectList(query);
    }

    @Override
    public List<User> listBySex(String sex) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("sex", sex);

        return userMapper.selectByMap(map);
    }

    @Override
    public PageResult pageQuery(PageDTO pageDTO) {
        Page<User> page = new Page<User>(pageDTO.getPageNum(), pageDTO.getPageSize());
        IPage<User> userIPage = userMapper.selectPage(page, null);

        PageResult pageResult = new PageResult();
        pageResult.setTotal(userIPage.getTotal());
        pageResult.setList(userIPage.getRecords());

        return pageResult;
    }

    @Override
    public User newUpdate(UpdateUserDTO user) {
        User newUser = userMapper.selectById(user.getId());

        if (newUser == null) {
            log.error("查无此用户");
        } else {
//           修改信息复制，排除空值覆盖，手动复制
//            BeanUtils.copyProperties(user, newUser, "id");
            if (user.getSex() != null && !user.getSex().isEmpty()) {
                newUser.setSex(user.getSex());
            }

            if (user.getPassword() != null && !user.getPassword().isEmpty()){
                newUser.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            }

            if (user.getName() != null && !user.getName().isEmpty()){
                newUser.setName(user.getName());
            }

            if (user.getPhone()!= null &&!user.getPhone().isEmpty()){
                newUser.setPhone(user.getPhone());
            }

            int i = userMapper.updateById(newUser);

            if (i > 0) {
                return newUser;
            }
        }
        log.error("修改失败");
        return null;
    }

    @Override
    public User updateAvatar(Integer id, MultipartFile avatar) {
        String avatarPath = commonService.upload(avatar);

        if (avatarPath == null || avatarPath.isEmpty()) {
            log.error("头像上传失败");
        }

        User userToUpdate = new User();
        userToUpdate.setId(id);
        userToUpdate.setAvatar(avatarPath);

        int rowsAffected = userMapper.update(userToUpdate,
                Wrappers.<User>lambdaUpdate().eq(User::getId, id));

        if (rowsAffected > 0) {
            return userMapper.selectById(id);
        } else {
            return null;
        }
    }

    @Override
    public BalanceVO getBalance(Integer id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            log.error("查无此用户");

            return null;
        } else {
            BalanceVO balanceVO = new BalanceVO();

            BeanUtils.copyProperties(user, balanceVO);

            return balanceVO;
        }
    }

    @Override
    public BalanceVO recharge(Integer id, Double money) {
        User user = userMapper.selectById(id);
        if (user == null) {
            log.error("{}用户不存在", id);

            return null;
        } else {
            if (money < 0) {
                log.error("充值金额不能小于0");

                return null;
            }

            user.setBalance(user.getBalance() + money);

            int i = userMapper.updateById(user);
            if (i > 0) {
                BalanceVO balanceVO = new BalanceVO();
                BeanUtils.copyProperties(user, balanceVO);

                return balanceVO;
            } else {
                log.error("数据修改失败");

                return null;
            }
        }

    }

    @Override
    public User consume(Integer id, Double money) {
        User user = userMapper.selectById(id);
        if (user == null) {
            log.error("{}用户不存在", id);

            return null;
        } else {
            if (user.getBalance() < money) {
                log.error("余额不足");

                return null;
            }

            user.setBalance(user.getBalance() - money);
            user.setIntegral(user.getIntegral() + money.intValue());
            int i = userMapper.updateById(user);

            if (i > 0){
                return user;
            }
        }

        return null;
    }
}




